package cn.micai.base.io;

import java.io.File;

/**
 * 描述：How to get extension of file in java
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/7 9:49
 */
public class GetExtensionOfFileMain {

    public static void main(String [] args) {
        ClassLoader classLoader = GetExtensionOfFileMain.class.getClassLoader();

        File file = new File(classLoader.getResource("test.txt").getFile());
        String fileExtension = getExtensionOfFile(file);
        System.out.println("File extension for test.txt is "+ fileExtension);

        File httpFile = new File(classLoader.getResource("HTTP Request.jmx").getFile());
        String extensionOfFile = getExtensionOfFile(httpFile);
        System.out.println("File extension for HTTP Request.jmx is "+ extensionOfFile);

        File folder=new File("src/main/resources");
        String fileExtensionFolder=getExtensionOfFile(folder);
        System.out.println("File extension for src/main/resources is "+fileExtensionFolder);
    }

    private static String getExtensionOfFile(File file) {
        String fileExtension = "";
        // Get file Name first
        String fileName = file.getName();
        // If fileName do not contain "." or starts with "." then it is not a valid file
        if (fileName.contains(".") && fileName.lastIndexOf(".") != 0) {
            fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        }
        return fileExtension;
    }
}
